<?php

defined('BASEPATH') or die('No direct script access allowed');

/**
 * 预算
 * @author  Karson
 * @name    budget.php
 * @since   2013-7-24 22:37:19
 */
class Budget_Controller extends Controller {
    
    function _init() {
        check_level();
    }
    
    function index() {
        $data['out'] = get_category_list('expense');
        $begintime = get_unixtime('year');
        $endtime = get_unixtime('year', 0, 'end');
        $where = array();
        $where[] = "user_id='{$this->auth->user_id}'";
        $where[] = "type='expense' AND occurtime>={$begintime} AND occurtime<={$endtime}";
        $where = implode(' AND ', $where);
        $real = $budget = array('expense' => array());
        $this->db->query("SELECT SUM(amount) AS amounts, category_id, DATE_FORMAT(FROM_UNIXTIME(occurtime), '%m') AS `month` FROM {pre}bill
            WHERE {$where}
            GROUP BY month,category_id WITH ROLLUP", 'lii');
        while ($row = $this->db->get_array('lii')) {
            if ($row['category_id'] == '') {
                $real['expense'][$month]['all'] = (int) $row['amounts'];
            } else {
                $month = $row['month'];
                $category = get_category($row['category_id']);
                if ($category) {
                    $father_id = $category['father_id'];
                    if (isset($real['expense'][$month][$father_id])) {
                        $real['expense'][$month][$father_id] += (int) $row['amounts'];
                    } else {
                        $real['expense'][$month][$father_id] = (int) $row['amounts'];
                    }
                }
            }
            if ($row['month'] == '' && $row['category_id'] == '') {
                $real['expense']['total'] = (int) $row['amounts'];
            }
        }
        $year = date("Y");
        $this->db->query("SELECT `month`, `content` FROM {pre}budget WHERE year='{$year}' AND user_id='{$this->auth->user_id}'");
        while ($row = $this->db->get_array()) {
            $row['month'] = (int) $row['month'];
            $content = json_decode($row['content'], true);
            $budget['expense'][$row['month']] = isset($content['expense']) ? $content['expense'] : array();
            $budget['expense'][$row['month']]['all'] = array_sum($budget['expense'][$row['month']]);
        }
        $data['real'] = $real;
        $data['budget'] = $budget;
        $data['year'] = date("Y");
        render("budget/index", $data);
    }

    function add() {
        $curryear = date("Y");
        $currmonth = date("m");
        $prevmonth = date("m", get_unixtime('month', -1));
        $prevyear = $prevmonth == '01' ? $curryear - 1 : $curryear;
        $prevbudget = $this->db->one("SELECT * FROM {pre}budget WHERE year='{$prevyear}' AND month='{$prevmonth}' AND user_id='{$this->auth->user_id}'");
        $currbudget = $this->db->one("SELECT * FROM {pre}budget WHERE year='{$curryear}' AND month='{$currmonth}' AND user_id='{$this->auth->user_id}'");
        if ($this->form->is_submit()) {
            $expense = $this->input->post("expense");
            $value = array(
                'year' => $curryear, 'month' => $currmonth, 'content' => addslashes(json_encode(array('expense' => $expense))), 'user_id' => $this->auth->user_id
            );
            if ($currbudget) {
                $this->db->update("{pre}budget", $value, array('id' => $currbudget['id']));
            } else {
                $value['uuid'] = get_uuid();
                $value['createtime'] = TIME;
                $this->db->insert("{pre}budget", $value);
            }
            $status = 'y';
            $info = '添加成功！';
            $data = $value;
            dialog_output($status, $info, $data);
        }
        $currbudget['content'] = $currbudget ? json_decode($currbudget['content'], true) : array();
        $prevbudget['content'] = $prevbudget ? json_decode($prevbudget['content'], true) : array();
        $data = array('curryear' => $curryear, 'currmonth' => $currmonth, 'prevyear' => $prevyear, 'prevmonth' => $prevmonth);
        $begintime = get_unixtime('month', -1);
        $endtime = get_unixtime('month', 0, 'end');
        $bugdet = array('expense' => array());
        $real = array('expense' => array());
        $this->db->safequery = false;
        $this->db->query("SELECT SUM(amount) AS amounts, category_id, DATE_FORMAT(FROM_UNIXTIME(occurtime), '%m') AS `month` FROM {pre}bill
            WHERE user_id='{$this->auth->user_id}' AND type='expense' AND occurtime>={$begintime} AND occurtime<={$endtime}
            GROUP BY month,category_id WITH ROLLUP", "bdl");
        while ($row = $this->db->get_array("bdl")) {
            $month = sprintf("%02d", $row['month']);
            if ($row['category_id'] == '') {
                $real['expense'][$month]['all'] = $row['amounts'];
            } else {
                $categoryinfo = get_category($row['category_id']);
                if ($categoryinfo) {
                    $tempid = $categoryinfo['father_id'] ? $categoryinfo['father_id'] : $categoryinfo['id'];
                    $real['expense'][$month][$tempid] = $row['amounts'];
                }
            }
            if ($row['month'] == '00' && $row['category_id'] == '') {
                $real['expense']['total'] = $row['amounts'];
            }
        }
        $prevbudget['content']['expense']['all'] = $prevbudget['content'] ? array_sum($prevbudget['content']['expense']) : 0;
        $currbudget['content']['expense']['all'] = $currbudget['content'] ? array_sum($currbudget['content']['expense']) : 0;
        $budget['expense'][$prevmonth] = $prevbudget['content']['expense'];
        $budget['expense'][$currmonth] = $currbudget['content']['expense'];
        $data['real'] = $real;
        $data['budget'] = $budget;
        $data['out'] = get_category_list('expense');
        render("budget/add", $data);
    }

    function copy($category_id = null) {
        if ($this->form->is_submit()) {
            $data = null;
            $curryear = date("Y");
            $currmonth = date("m");
            $prevmonth = date("m", get_unixtime('month', -1));
            $prevyear = $prevmonth == '01' ? $curryear - 1 : $curryear;
            $prevbudget = $this->db->one("SELECT * FROM {pre}budget WHERE year='{$prevyear}' AND month='{$prevmonth}' AND user_id='{$this->auth->user_id}'");
            $currbudget = $this->db->one("SELECT * FROM {pre}budget WHERE year='{$curryear}' AND month='{$currmonth}' AND user_id='{$this->auth->user_id}'");
            if ($prevbudget) {
                $value = array('user_id' => $this->auth->user_id, 'year' => $curryear, 'month' => $currmonth);
                if ($category_id) {
                    if ($currbudget) {
                        $prevcontent = json_decode($prevbudget['content'], true);
                        $content = json_decode($currbudget['content'], true);
                        if (isset($content['expense'][$category_id])) {
                            $content['expense'][$category_id] = isset($prevcontent['expense'][$category_id]) ? $prevcontent['expense'][$category_id] : 0;
                            $value['content'] = addslashes(json_encode($content));
                            $this->db->update("{pre}budget", $value, array('id' => $currbudget['id']));
                            $status = 'y';
                            $info = '复制成功！';
                            $data = $content['expense'][$category_id];
                        } else {
                            $status = 'n';
                            $info = '未找到上月数据！';
                        }
                    } else {
                        $content = json_decode($prevbudget['content'], true);
                        if (isset($content['expense'][$category_id])) {
                            foreach ($content['expense'] as $k => & $v) {
                                $v = $k == $category_id ? $content['expense'][$category_id] : 0;
                            }
                            $value['content'] = addslashes(json_encode($content));
                            $value['createtime'] = TIME;
                            $value['uuid'] = get_uuid();
                            $this->db->insert("{pre}budget", $value);
                            $status = 'y';
                            $info = '复制成功！';
                            $data = $content['expense'][$category_id];
                        } else {
                            $status = 'n';
                            $info = '未找到上月数据！';
                        }
                    }
                } else {
                    if ($currbudget) {
                        $value['content'] = addslashes($prevbudget['content']);
                        $this->db->update("{pre}budget", $value, array('id' => $currbudget['id']));
                    } else {
                        $value['content'] = addslashes($prevbudget['content']);
                        $value['createtime'] = TIME;
                        $value['uuid'] = get_uuid();
                        $this->db->insert("{pre}budget", $value);
                    }
                    $status = 'y';
                    $info = '复制成功！';
                }
            } else {
                $status = 'n';
                $info = '无上月预算数据,复制失败';
            }
            dialog_output($status, $info, $data);
        }
    }

    function clear($category_id = null) {
        if ($this->form->is_submit()) {
            $data = null;
            $curryear = date("Y");
            $currmonth = date("m");
            $currbudget = $this->db->one("SELECT * FROM {pre}budget WHERE year='{$curryear}' AND month='{$currmonth}' AND user_id='{$this->auth->user_id}'");
            if ($currbudget) {
                $content = json_decode($currbudget['content'], true);
                if ($category_id) {
                    if (isset($content['expense'][$category_id])) {
                        $content['expense'][$category_id] = 0;
                        $value['content'] = addslashes(json_encode($content));
                        $this->db->update("{pre}budget", $value, array('id' => $currbudget['id']));
                        $status = 'y';
                        $info = '清空成功！';
                        $data = 0;
                    } else {
                        $status = 'n';
                        $info = '无需清除！';
                    }
                } else {
                    $this->db->delete("{pre}budget", array('id' => $currbudget['id']));
                    $status = 'y';
                    $info = '清空成功！';
                }
            } else {
                $status = 'n';
                $info = '未找到预算数据,清空失败';
            }
            dialog_output($status, $info, $data);
        }
    }

}